<template>
  <div class="time-config-container">
    <VCard elevation="2">
      <VCardTitle class="d-flex align-center">
        <VIcon icon="mdi-clock-outline" class="mr-2" />
        时间配置管理
      </VCardTitle>
      <VCardText>
        <VTabs v-model="activeTab">
          <VTab value="working-hours">
            <VIcon icon="mdi-clock-time-eight" class="mr-2" />
            工作时间配置
          </VTab>
          <VTab value="intervals">
            <VIcon icon="mdi-timer-outline" class="mr-2" />
            间隔时间配置
          </VTab>
        </VTabs>
        <VWindow v-model="activeTab">
          <!-- 工作时间配置 -->
          <VWindowItem value="working-hours">
            <div class="mt-6">
              <div class="d-flex justify-space-between align-center mb-4">
                <h3 class="text-h6">工作时间段设置</h3>
              </div>
              <VDataTable
                :headers="workingHoursHeaders"
                :items="workingHoursConfigs"
                :loading="loading"
                class="elevation-1"
                density="comfortable"
                :no-data-text="$t('noDataText')"
              >
                <template #item.name="{ item }">
                  <div class="d-flex align-center">
                    <VIcon icon="mdi-clock-outline" class="mr-2" size="small" />
                    <span class="font-weight-medium">{{ item.name }}</span>
                  </div>
                </template>
                <template #item.timeRange="{ item }">
                  <div class="d-flex align-center">
                    <VChip size="small" color="primary" class="mr-2">
                      <VIcon icon="mdi-clock-start" size="small" class="mr-1" />
                      {{ item.startTime || '未设置' }}
                    </VChip>
                    <VIcon icon="mdi-arrow-right" size="small" class="mx-1" />
                    <VChip size="small" color="secondary">
                      <VIcon icon="mdi-clock-end" size="small" class="mr-1" />
                      {{ item.endTime || '未设置' }}
                    </VChip>
                  </div>
                  <div class="text-caption text-medium-emphasis mt-1">
                    持续时间：{{ calculateDuration(item.startTime, item.endTime) }}
                  </div>
                </template>
                <template #item.days="{ item }">
                  <div class="d-flex flex-wrap">
                    <VChip 
                      v-for="day in formatWorkingDays(item.days || '')" 
                      :key="day"
                      size="small" 
                      color="success"
                      class="mr-1 mb-1"
                    >
                      {{ day }}
                    </VChip>
                  </div>
                </template>
                <template #item.description="{ item }">
                  <div class="text-body-2" style="max-width: 200px;">
                    {{ item.description || '无描述' }}
                  </div>
                </template>
                <template #item.isActive="{ item }">
                  <VSwitch
                    v-model="item.isActive"
                    @change="updateConfigStatus(item.id!, item.isActive)"
                    density="compact"
                    hide-details
                    color="primary"
                  />
                </template>
                <template #item.actions="{ item }">
                  <VBtn
                    icon="mdi-delete"
                    size="default"
                    variant="tonal"
                    color="error"
                    @click.stop="deleteConfig(item.id!)"
                  />
                </template>
              </VDataTable>
            </div>
          </VWindowItem>
          <!-- 间隔时间配置 -->
          <VWindowItem value="intervals">
            <div class="mt-6">
              <div class="d-flex justify-space-between align-center mb-4">
                <h3 class="text-h6">间隔时间设置</h3>
              </div>
              <VDataTable
                :headers="intervalHeaders"
                :items="intervalConfigs"
                :loading="loading"
                class="elevation-1"
                density="comfortable"
                :no-data-text="$t('noDataText')"
              >
                <template #item.name="{ item }">
                  <div class="d-flex align-center">
                    <VIcon icon="mdi-timer-outline" class="mr-2" size="small" />
                    <span class="font-weight-medium">{{ item.name }}</span>
                  </div>
                </template>
                <template #item.timeDetails="{ item }">
                  <div class="d-flex flex-column">
                    <div class="d-flex align-center mb-1">
                      <VChip size="small" color="info" class="mr-2">
                        <VIcon icon="mdi-timer" size="small" class="mr-1" />
                        持续：{{ item.duration || '未设置' }}{{ item.duration ? '分钟' : '' }}
                      </VChip>
                      <VChip size="small" color="warning">
                        <VIcon icon="mdi-clock-outline" size="small" class="mr-1" />
                        间隔：{{ item.intervalMinutes || '未设置' }}{{ item.intervalMinutes ? '分钟' : '' }}
                      </VChip>
                    </div>
                    <div class="text-caption text-medium-emphasis">
                      <span v-if="item.duration && item.intervalMinutes">
                        实际可用时间：{{ item.duration }}分钟 / 总时间：{{ item.intervalMinutes }}分钟
                      </span>
                      <span v-else>
                        时间配置不完整
                      </span>
                    </div>
                  </div>
                </template>
                <template #item.description="{ item }">
                  <div class="text-body-2" style="max-width: 200px;">
                    {{ item.description || '无描述' }}
                  </div>
                </template>
                <template #item.isActive="{ item }">
                  <VSwitch
                    v-model="item.isActive"
                    @change="updateConfigStatus(item.id!, item.isActive)"
                    density="compact"
                    hide-details
                    color="primary"
                  />
                </template>
                <template #item.actions="{ item }">
                  <VBtn
                    icon="mdi-delete"
                    size="default"
                    variant="tonal"
                    color="error"
                    @click.stop="deleteConfig(item.id!)"
                  />
                </template>
              </VDataTable>
            </div>
          </VWindowItem>
        </VWindow>
      </VCardText>
    </VCard>
    <!-- 删除确认对话框 -->
    <VDialog v-model="deleteDialog" max-width="400px" @keydown.esc="deleteDialog = false" @click:outside="deleteDialog = false">
      <VCard>
        <VCardTitle class="d-flex align-center text-warning">
          <VIcon icon="mdi-alert" class="mr-2" />
          确认删除
        </VCardTitle>
        <VCardText>
          <p class="text-body-1">您确定要删除这个时间配置吗？</p>
          <p class="text-body-2 text-error">此操作无法撤销。</p>
        </VCardText>
        <VCardActions>
          <VSpacer />
          <VBtn @click="deleteDialog = false">取消</VBtn>
          <VBtn color="error" @click="confirmDelete">确认删除</VBtn>
        </VCardActions>
      </VCard>
    </VDialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useSnackbarStore } from '@/store/snackbarStore';
import { 
  TimeConfig, 
  getTimeConfigsByType, 
  deleteTimeConfig, 
  updateTimeConfigStatus,
  formatWorkingDays
} from '@/api/timeConfig';

const snackbarStore = useSnackbarStore();

// 响应式数据
const activeTab = ref('working-hours');
const loading = ref(false);
const workingHoursConfigs = ref<TimeConfig[]>([]);
const intervalConfigs = ref<TimeConfig[]>([]);

// 对话框控制
const deleteDialog = ref(false);
const deleteConfigId = ref<number | null>(null);

// 表格头部
const workingHoursHeaders = [
  { title: '名称', key: 'name', width: '200px' },
  { title: '时间范围', key: 'timeRange', width: '300px' },
  { title: '工作日', key: 'days', width: '200px' },
  { title: '描述', key: 'description', width: '250px' },
  { title: '状态', key: 'isActive', width: '100px' },
  { title: '操作', key: 'actions', sortable: false, width: '100px' }
];

const intervalHeaders = [
  { title: '名称', key: 'name', width: '200px' },
  { title: '时间详情', key: 'timeDetails', width: '350px' },
  { title: '描述', key: 'description', width: '250px' },
  { title: '状态', key: 'isActive', width: '100px' },
  { title: '操作', key: 'actions', sortable: false, width: '100px' }
];

// 计算持续时间的方法
const calculateDuration = (startTime: string, endTime: string) => {
  if (!startTime || !endTime) {
    return '未设置';
  }
  
  // 处理可能的时间格式问题
  const timeRegex = /^(\d{1,2}):(\d{2})(:(\d{2}))?$/;
  const startMatch = startTime.match(timeRegex);
  const endMatch = endTime.match(timeRegex);
  
  if (!startMatch || !endMatch) {
    return '时间格式错误';
  }
  
  const startH = parseInt(startMatch[1]);
  const startM = parseInt(startMatch[2]);
  const endH = parseInt(endMatch[1]);
  const endM = parseInt(endMatch[2]);
  
  const startTotal = startH * 60 + startM;
  const endTotal = endH * 60 + endM;
  const durationMinutes = endTotal - startTotal;
  
  if (durationMinutes < 0) {
    return '时间设置错误';
  }
  
  const hours = Math.floor(durationMinutes / 60);
  const minutes = durationMinutes % 60;
  
  if (hours > 0) {
    return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`;
  } else {
    return `${minutes}分钟`;
  }
};

// 方法
const loadConfigs = async () => {
  loading.value = true;
  try {
    console.log('开始加载时间配置数据...');
    
    const workingHours = await getTimeConfigsByType('WORKING_HOURS');
    const intervals = await getTimeConfigsByType('INTERVAL');
    
    console.log('工作时间配置响应:', workingHours);
    console.log('间隔时间配置响应:', intervals);
    
    // 检查响应格式并处理数据
    if (workingHours && workingHours.success) {
      workingHoursConfigs.value = workingHours.data || [];
      console.log('工作时间配置数据:', workingHoursConfigs.value);
      // 详细调试每个配置项
      workingHoursConfigs.value.forEach((config, index) => {
        console.log(`工作时间配置 ${index}:`, {
          id: config.id,
          name: config.name,
          startTime: config.startTime,
          endTime: config.endTime,
          description: config.description,
          isActive: config.isActive
        });
      });
    } else {
      console.error('工作时间配置加载失败:', workingHours);
      workingHoursConfigs.value = [];
    }
    
    if (intervals && intervals.success) {
      intervalConfigs.value = intervals.data || [];
      console.log('间隔时间配置数据:', intervalConfigs.value);
      // 详细调试每个配置项
      intervalConfigs.value.forEach((config, index) => {
        console.log(`间隔时间配置 ${index}:`, {
          id: config.id,
          name: config.name,
          duration: config.duration,
          intervalMinutes: config.intervalMinutes,
          description: config.description,
          isActive: config.isActive
        });
      });
    } else {
      console.error('间隔时间配置加载失败:', intervals);
      intervalConfigs.value = [];
    }
    
    if (workingHoursConfigs.value.length === 0 && intervalConfigs.value.length === 0) {
      snackbarStore.showMessage('没有找到时间配置数据，请检查数据库连接', 'warning');
    }
  } catch (error: any) {
    console.error('加载配置失败:', error);
    snackbarStore.showMessage('加载配置失败: ' + error.message, 'error');
  } finally {
    loading.value = false;
  }
};

const updateConfigStatus = async (id: number, isActive: boolean) => {
  try {
    const result = await updateTimeConfigStatus([id], isActive);
    if (result.success) {
      snackbarStore.showMessage('状态更新成功', 'success');
    } else {
      snackbarStore.showMessage(result.message || '状态更新失败');
      await loadConfigs(); // 重新加载以恢复状态
    }
  } catch (error: any) {
    snackbarStore.showMessage('状态更新失败');
    await loadConfigs(); // 重新加载以恢复状态
  }
};

const deleteConfig = (id: number) => {
  deleteConfigId.value = id;
  deleteDialog.value = true;
};

const confirmDelete = async () => {
  if (!deleteConfigId.value) return;
  
  try {
    const result = await deleteTimeConfig(deleteConfigId.value);
    if (result.success) {
      snackbarStore.showMessage('删除成功', 'success');
      deleteDialog.value = false;
      await loadConfigs();
    } else {
      snackbarStore.showMessage(result.message || '删除失败');
    }
  } catch (error: any) {
    snackbarStore.showMessage('删除失败');
  }
};

// 生命周期
onMounted(() => {
  loadConfigs();
});
</script>

<style scoped>
.time-config-container {
  padding: 20px;
}

.v-data-table {
  border-radius: 8px;
}

.v-chip {
  margin-right: 4px;
}

.v-dialog .v-card {
  border-radius: 12px;
}

.text-medium-emphasis {
  opacity: 0.7;
}

.v-data-table :deep(.v-data-table__td) {
  padding: 12px 16px;
}

.v-data-table :deep(.v-data-table__th) {
  padding: 12px 16px;
}
</style> 
